package userlogic

import (
	"context"
	"time"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/schema"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"
	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterAdminLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterAdminLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterAdminLogic {
	return &RegisterAdminLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterAdminLogic) RegisterAdmin(in *login_rpc.RegisterAdminRequest) (*login_rpc.RegisterAdminResponse, error) {
	var commonResp login_rpc.CommonResp
	if in.Account == "" || in.Password == "" || in.Role == 0 || in.Nickname == "" {
		commonResp.Code = config.ParameterError
		commonResp.Message = "wrong parameter"
		return &login_rpc.RegisterAdminResponse{CommonResp: &commonResp, UserId: 0}, nil
	}

	// 检查账号是否已存在
	admin, _ := model.NewAdminUserModel(l.ctx, l.svcCtx.Db).GetAdminUserByAccount(in.Account)
	if admin.Id > 0 {
		commonResp.Code = config.BasicError
		commonResp.Message = "duplicated account"
		return &login_rpc.RegisterAdminResponse{CommonResp: &commonResp, UserId: 0}, nil
	}

	var adminUser schema.AdminUser
	adminUser.Account = in.Account
	adminUser.Password = HashPassword(in.Password)
	adminUser.Role = in.Role
	adminUser.Nickname = in.Nickname
	adminUser.UserStatus = in.UserStatus
	adminUser.HeadPictureUrl = in.HeadPictureUrl
	adminUser.RegisterAt = time.Now().Unix()
	adminUser.IsOpenGoogle = 0
	err := model.NewAdminUserModel(l.ctx, l.svcCtx.Db).InsertSchema(&adminUser)
	if err != nil {
		logx.Errorf("InsertSchema req: %v error: %v", in, err)
		commonResp.Code = config.DBError
		commonResp.Message = "failed to add user"
		return &login_rpc.RegisterAdminResponse{CommonResp: &commonResp}, nil
	}

	return &login_rpc.RegisterAdminResponse{CommonResp: &commonResp, UserId: adminUser.Id}, nil
}
